<?php
class PostsController extends Controller
{
	public $layout = 'main';
	
	/*public function init()
	{
		if(!$this->hasPermission('manage posts')) echo 'kdkdk';	
	}

	public function filters()
	{
		return array(
			'accessControl', 
		);
	}

	public function accessRules()
    {
        return array(
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('index','create','update','delete','updatestatus'),
                'users'=>array('*'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }*/

	public function actionIndex()
	{
		//get params
		$strTaxonomyCode =  Yii::app()->request->getParam('taxonomy', null);
		$intPage 		= Yii::app()->request->getParam('page', 1);
		$intRowsPerPage = Yii::app()->request->getParam('rpp', MIN_ROWS_PER_PAGE);
		$intSortType 	= Yii::app()->request->getParam('sort',-1);
		
		//load taxonomy
		$intTaxonomyId = null;
		$arrTaxonomies = Taxonomies::getInstance()->getList();
		foreach($arrTaxonomies as $R){
			if($strTaxonomyCode == $R['taxonomy_code'])	$intTaxonomyId = $R['taxonomy_id'];
		}
		if($intTaxonomyId === null) die('Invalid post type');
		
		//query posts
		$args = array(
			'taxonomy_id' => $intTaxonomyId,
			'keyword' =>  '%'.Yii::app()->request->getParam('q', null).'%',
			'category_id' => Yii::app()->request->getParam('cat', null),
			'post_status' => Yii::app()->request->getParam('status', null),
			/*'created_date' => array(
				'from' => Yii::app()->request->getParam('dfrom', null),
				'to' => Yii::app()->request->getParam('dto', null)
			),*/
			'page' => $intPage,
			'limit' => $intRowsPerPage
		);
		$arrPosts = Posts::getInstance()->getList($args);
		$intTotalRows = isset($arrPosts[0]['total_rows'])?$arrPosts[0]['total_rows']:0;
		$args['keyword'] = trim($args['keyword'], '%');
		
		//pagination
		$objPages=new CPagination($intTotalRows);
		$objPages->setCurrentPage($intPage-1);
		$objPages->setPageSize($intRowsPerPage);
		
		//render view
		if($strTaxonomyCode == 'page'){
			$this->render('index-page', array(
				'arrPosts' => $arrPosts,
				'objPages' => $objPages,
				'args' => $args,
				'arrPostStatus' => Posts::getInstance()->getListStatus()
			));
		} else {
			$arrCategories = Categories::getInstance()->getByParent();
			$this->render('index', array(
				'arrPosts' => $arrPosts,
				'objPages' => $objPages,
				'arrCategories' => $arrCategories,
				'args' => $args,
				'arrPostStatus' => Posts::getInstance()->getListStatus(),
				'type' => $strTaxonomyCode
			));
		}
		$this->setUrl();
	}
	
	public function actionForm()
	{
		$intPostId = Yii::app()->request->getParam('id', null);
		$strTaxonomyCode =  Yii::app()->request->getParam('taxonomy', null);
		//update post
		if(Yii::app()->request->isPostRequest)
		{
			//get param
			$arrParams = Yii::app()->request->getParam('post', null); 
			$arrParams['post_published_date'] = !empty($arrParams['post_published_date'])?@date('Y-m-d H:i:s', strtotime($arrParams['post_published_date'])):null;
			$arrParams['post_expiry_date'] = !empty($arrParams['post_expiry_date'])?@date('Y-m-d H:i:s', strtotime($arrParams['post_expiry_date'])):null;

			$refresh = false;

			//insert/update
			if(empty($intPostId)){
				$arrParams['post_creator_id'] = Yii::app()->admin->id;
				$intResult = Posts::getInstance()->insert($arrParams);
				$intPostId = $intResult;
				$refresh = true;
			}
			else{
				$arrParams['post_last_modifier_id'] = Yii::app()->admin->id;
				$intResult = Posts::getInstance()->update($intPostId, $arrParams);
			}

			if($intResult > 0){
				//udpate category
				$arrCategoryIds = Yii::app()->request->getParam('category', null); 
				if(!empty($arrCategoryIds)){
					Posts::getInstance()->updateCategory($intPostId, $arrCategoryIds);
				}
				//update tags
				$strTags = Yii::app()->request->getParam('tags', null);
				if(!empty($strTags)){
					Posts::getInstance()->updateTags($intPostId, $strTags);
				}
				//update custom fields
				$arrFields = Yii::app()->request->getParam('fields', null);
				if(is_array($arrFields)){
					foreach($arrFields as $intFieldId => $strFieldValue){
						$strFieldValue = trim($strFieldValue);
						if(!empty($intFieldId)){
							Posts::getInstance()->updateField($intPostId, $intFieldId, $strFieldValue);
						}
					} 					
				}
				//done
				Yii::app()->admin->setFlash('ok', Yii::t('admincp', 'Updated successfully!'));
				if($refresh){
					$this->refresh();
				} else{
					header('Location:'.$this->getUrl());
					exit;
				}
			}
		}
		//load taxonomy
		$intTaxonomyId = null;
		$arrTaxonomies = Taxonomies::getInstance()->getList();
		foreach($arrTaxonomies as $R){
			if($strTaxonomyCode == $R['taxonomy_code'])	$intTaxonomyId = $R['taxonomy_id'];
		}
		
		//load form
		$arrItemInfo = array();
		if(!empty($intPostId)){
			$arrItemInfo = Posts::getInstance()->get($intPostId);
			$arrItemInfo['post_category_id'] = !empty($arrItemInfo['post_category_id'])?explode(',', $arrItemInfo['post_category_id']):array();
			$strTaxonomyCode = $arrItemInfo['taxonomy_code'];
			$intTaxonomyId = $arrItemInfo['taxonomy_id'];
		}
		if($intTaxonomyId === null) die('Invalid post type');
		$arrCustomFields = Taxonomies::getInstance()->getListFields($intTaxonomyId);
		//render layout
		if($strTaxonomyCode == 'page'){
			$this->render('form-page', array(
				'arrItemInfo' => $arrItemInfo
			));
		} else {
			$arrCategories = Categories::getInstance()->getByParent();
			$this->render('form', array(
				'arrItemInfo' => $arrItemInfo,
				'arrCategories' => $arrCategories,
				'arrCustomFields' => $arrCustomFields,
				'intTaxonomyId' => $intTaxonomyId				
			));
		}
	}
	
	public function actionDelete(){
		$intPostId = Yii::app()->request->getParam('id', null);
		if(!empty($intPostId))
			$result = Posts::getInstance()->delete($intPostId);
		header('Location:'.$this->getUrl());
		exit;
	}

}